package com.example.myapplication.ui.inspection;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;
import com.example.myapplication.bean.Inspection;
import com.example.myapplication.service.InspectionService;
import com.example.myapplication.ui.component.CustomToast;
import com.example.myapplication.util.StringUtils;

import java.util.Calendar;

public class InspectionInput extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "InspectionInput";
    private TextView dataShowArea;
    private TextView timeShowArea;
    private TextView classShowArea;
    private TextView categoryText;
    private TextView equipmentText;
    private TextView groupText;
    private TextView personText;
    private TextView situationText;
    private TextView abnormalText;
    private ImageButton calendarBtn;
    private Dialog bottomDialog;
    private DatePicker datePicker;
    private TimePicker timePicker;
    private Spinner classSpinner;
    private Spinner equipmentSpinner;
    private LinearLayout commitBtn;
    private CustomToast toast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_inspection_input);
        dataShowArea = findViewById(R.id.date_show_area);
        timeShowArea = findViewById(R.id.time_show_area);
        classShowArea = findViewById(R.id.class_show_area);
        categoryText = findViewById(R.id.category_text);
        equipmentText = findViewById(R.id.equipment_text);
        groupText = findViewById(R.id.group_text);
        personText = findViewById(R.id.person_text);
        personText.setText(getIntent().getStringExtra("name"));
        situationText = findViewById(R.id.situation_text);
        abnormalText = findViewById(R.id.abnormal_text);
        calendarBtn = findViewById(R.id.calendar_btn);
        classSpinner = findViewById(R.id.class_spinner);
        equipmentSpinner = findViewById(R.id.equipment_spinner);
        commitBtn = findViewById(R.id.commit_inspection);
        calendarBtn.setOnClickListener(this);
        commitBtn.setOnClickListener(this);
        initDataTimeShowArea();
        setClassSpinnerListener();
        setEquipmentSpinnerListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.calendar_btn:
                showBottomDialog();
                loadDataPickerAndTimePicker();
                setDatePickerListenerAndGetInfo();
                setTimePickerListenerAndGetInfo();
                break;
            case R.id.commit_inspection:
                openCommitDialog();
                break;

        }
    }

    private void showBottomDialog() {
        bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_content, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
    }

    private void loadDataPickerAndTimePicker() {
        datePicker = bottomDialog.findViewById(R.id.date_picker);
        timePicker = bottomDialog.findViewById(R.id.time_picker);
    }

    public void setDatePickerListenerAndGetInfo() {
        int year = 0;
        int month = 0;
        int day = 0;

        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DATE);
        datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                setDataShowArea(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        });

    }

    public void setTimePickerListenerAndGetInfo() {

        timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                setTimeShowArea(hourOfDay + " " + ":" + " " + minute);
            }
        });


    }

    public void initDataTimeShowArea() {
        int year = 0;
        int month = 0;
        int day = 0;
        int hour = 0;
        int minute = 0;
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        day = calendar.get(Calendar.DATE);
        hour = calendar.get(Calendar.HOUR);
        minute = calendar.get(Calendar.MINUTE);
        setDataShowArea(year + "-" + month + "-" + day);
        setTimeShowArea(hour + " " + ":" + " " + minute);

    }


    public void setDataShowArea(String pickData) {
        dataShowArea.setText(pickData);
    }

    public void setCategoryText(String pickCategory) {
        categoryText.setText(pickCategory);
    }

    public void setTimeShowArea(String pickTime) {
        timeShowArea.setText(pickTime);
    }

    public void setClassSpinnerListener() {
        classSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String[] classArray = getResources().getStringArray(R.array.classItem);
                setClassShowArea(classArray[position]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    public void setEquipmentSpinnerListener() {
        equipmentSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String[] equipmentArray = getResources().getStringArray(R.array.equipment_category);
                setCategoryText(equipmentArray[position]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    public void setClassShowArea(String classInfo) {
        classShowArea.setText(classInfo);
    }

    public void openCommitDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(InspectionInput.this);
        builder.setTitle("提交确认");
        builder.setIcon(R.drawable.ic_commit);//设置标题图
        builder.setMessage("\n" + "   确定提交？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                if(isInputEmpty()){
                    toastMessage("输入不能为空！");
                    return;
                }
                int statusCode = 0;
                statusCode = commitInspection();
                showStatusAndRefreshInput(statusCode);
            }
        });
        builder.setNegativeButton("再改改", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                Toast.makeText(InspectionInput.this, "cancel", Toast.LENGTH_SHORT).show();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setBackgroundColor(Color.WHITE);
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLUE);
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setBackgroundColor(Color.WHITE);
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
    }

    private Integer commitInspection() {
        Inspection inspection = new Inspection(dataShowArea.getText().toString() + " " + timeShowArea.getText().toString(),
                classShowArea.getText().toString(),
                categoryText.getText().toString(),
                equipmentText.getText().toString(),
                groupText.getText().toString(),
                personText.getText().toString(),
                situationText.getText().toString(),
                abnormalText.getText().toString());
        return new InspectionService().addInspection(inspection);
    }

    private void toastMessage(String content) {
        if (toast != null) {
            toast.hide();
        }
        toast = new CustomToast(InspectionInput.this,
                (ViewGroup) this.findViewById(R.id.toast_custom_parent));
        toast.show(content, 1000);
    }

    public void refreshInputText() {
        classShowArea.setText("");
        categoryText.setText("");
        equipmentText.setText("");
        groupText.setText("");
        personText.setText("");
        situationText.setText("");
        abnormalText.setText("");

    }

    public void showStatusAndRefreshInput(Integer statusCode) {
        if (statusCode == 200) {
            toastMessage("添加成功");
        } else {
            toastMessage("添加失败");
        }
        refreshInputText();
    }

    public boolean isInputEmpty() {
        String classInfo = classShowArea.getText().toString();
        String categoryInfo = categoryText.getText().toString();
        String equipmentInfo = equipmentText.getText().toString();
        String groupInfo = groupText.getText().toString();
        String personName = personText.getText().toString();
        String situation = situationText.getText().toString();
        String abnormal = abnormalText.getText().toString();
        if (StringUtils.isEmpty(classInfo)||StringUtils.isEmpty(categoryInfo)||StringUtils.isEmpty(equipmentInfo)
        ||StringUtils.isEmpty(groupInfo)||StringUtils.isEmpty(personName)||StringUtils.isEmpty(situation)
        ||StringUtils.isEmpty(abnormal)){
            return true;
        }

        return false;
    }

}